const { prisma } = require('../config/prisma');

/**
 * 创建单个测试用户
 */
async function createSingleTestUser() {
  try {
    console.log('🚀 开始创建单个测试用户...');

    // 测试用户数据
    const testUserData = {
      openid: 'test_user_main_001',
      nickname: '测试用户',
      avatar_url: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
      phone_number: '13800138888',
      wechat_id: 'test_user_main',
      status: 'active',
      chat_banned: false,
      publishing_credits: 10,
      chat_credits: 50,
      contact_view_credits: 20,
      inviter_id: null
    };

    // 检查是否已存在测试用户
    const existingUser = await prisma.users.findUnique({
      where: { openid: testUserData.openid }
    });

    let user;
    if (existingUser) {
      console.log('⚠️ 测试用户已存在，更新用户信息...');
      user = await prisma.users.update({
        where: { openid: testUserData.openid },
        data: testUserData
      });
    } else {
      // 创建新的测试用户
      user = await prisma.users.create({
        data: testUserData
      });
    }

    console.log('✅ 测试用户创建/更新成功:');
    console.log(`   用户ID: ${user.id}`);
    console.log(`   OpenID: ${user.openid}`);
    console.log(`   昵称: ${user.nickname}`);
    console.log(`   状态: ${user.status}`);
    console.log(`   发布信用: ${user.publishing_credits}`);
    console.log(`   聊天信用: ${user.chat_credits}`);
    console.log(`   查看联系方式信用: ${user.contact_view_credits}`);

    // 确保全国总群存在
    console.log('📝 检查全国总群...');
    const totalGroup = await prisma.chat_groups.upsert({
      where: { id: 1 },
      create: {
        id: 1,
        group_name: '全国接单总群',
        description: '全国范围内的接单信息交流群',
        group_type: 'group'
      },
      update: {
        group_name: '全国接单总群',
        description: '全国范围内的接单信息交流群'
      }
    });

    // 将用户添加到全国总群
    console.log('📝 将用户添加到全国总群...');
    await prisma.group_members.upsert({
      where: {
        group_id_user_id: {
          group_id: totalGroup.id,
          user_id: user.id
        }
      },
      create: {
        group_id: totalGroup.id,
        user_id: user.id,
        role: 'member'
      },
      update: {
        role: 'member'
      }
    });

    console.log('✅ 用户已添加到全国总群');
    
    return user;

  } catch (error) {
    console.error('❌ 创建测试用户失败:', error);
    throw error;
  }
}

/**
 * 删除测试用户
 */
async function deleteSingleTestUser() {
  try {
    console.log('🗑️ 开始删除测试用户...');

    const result = await prisma.users.delete({
      where: { openid: 'test_user_main_001' }
    });

    console.log('✅ 测试用户删除成功');
    return result;

  } catch (error) {
    if (error.code === 'P2025') {
      console.log('⚠️ 测试用户不存在，无需删除');
    } else {
      console.error('❌ 删除测试用户失败:', error);
      throw error;
    }
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  const action = process.argv[2];
  
  if (action === 'delete') {
    deleteSingleTestUser()
      .then(() => process.exit(0))
      .catch(() => process.exit(1));
  } else {
    createSingleTestUser()
      .then(() => process.exit(0))
      .catch(() => process.exit(1));
  }
}

module.exports = {
  createSingleTestUser,
  deleteSingleTestUser
};